package com.tianjs.forkjoin_lab;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;

public class CountTask extends RecursiveTask<Integer> {

	private static final int THRESHOLD=2;//定义任务大小粒度
	
	private int start;
	
	private int end;
	
	@Override
	protected Integer compute() {
		int sum = 0;
		//如果任务足够小，就计算任务
		boolean canCompute = (end - start) <= THRESHOLD;
		if(canCompute) {
			for(int i=start;i<=end;i++) {
				sum = sum + i;
			}
		}else {
			//如果任务大于阈值，就分裂成2个子任务执行
			int middle = (start + end)/2;
			CountTask leftTask = new CountTask(start,middle);
			CountTask rightTask = new CountTask(middle+1,end);
			leftTask.fork();
			rightTask.fork();
			//执行子任务
			//等待子任务执行完，并得到结果
			int leftResult = leftTask.join();//等待子任务执行完成
			int rightResult = rightTask.join();
			//合并子任务
			sum = leftResult + rightResult;
		}
		return sum;
	}

	public CountTask(int start, int end) {
		this.start = start;
		this.end = end;
	}
	
	public static void main(String[] args) {
		ForkJoinPool forkJoinPool=new ForkJoinPool();
		//生成一个计算任务，负责计算1 + 2 + 3+4
		CountTask countTask = new CountTask(1,10);
		//执行一个任务
		Future<Integer> result = forkJoinPool.submit(countTask);
		try {
			if(countTask.isCompletedAbnormally()) {
				System.out.println(countTask.getException());
			}
			System.out.println(result.get());
		} catch (InterruptedException e) {
		} catch (ExecutionException e) {
		}
	}

}
